package com.donger.common.messgae.handler;

import cn.hutool.core.util.StrUtil;
import com.donger.common.core.exception.BizException;
import com.donger.common.messgae.handler.MessageHandler;
import com.donger.common.messgae.template.EmailTemplate;
import com.donger.common.messgae.template.SmsTemplate;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;


@Slf4j
public class JavaEmailMessaheHandler implements MessageHandler<EmailTemplate> {

    @Autowired
    private JavaMailSender mailSender;

    @Override
    public void check(EmailTemplate emailTemplate) throws Exception {
        if (StrUtil.isEmpty(emailTemplate.getAddress())) {
            throw new Exception("收件人不可为空");
        }
        if (StrUtil.isEmpty(emailTemplate.getContentTemplate())) {
            throw new Exception("邮件内容模板不能为空");
        }
        if(StrUtil.isEmpty(emailTemplate.getSubject())){
            throw new BizException("邮件主题不能为空");
        }

        if(StrUtil.isEmpty(emailTemplate.getFrom())){
            throw new BizException("发件人不能为空");
        }

    }

    @SneakyThrows
    @Override
    public boolean process(EmailTemplate emailTemplate) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
        //邮件发送人
        messageHelper.setFrom(emailTemplate.getFrom());
        //邮件接收人
        messageHelper.setTo(emailTemplate.getAddress());
        //邮件主题
        message.setSubject(emailTemplate.getSubject());
        //邮件内容，html格式
        messageHelper.setText(emailTemplate.getContentTemplate(), true);
        //发送
        mailSender.send(message);
        //日志信息
        log.info("邮件已经发送。");
        return false;
    }

    @Override
    public void fail(EmailTemplate emailTemplate) {
        log.error("邮件发送失败 -> {}",emailTemplate.toString());
    }
}
